package com.franklin.maven.localcleaner.repository;

import com.franklin.maven.localcleaner.threadpool.ThreadPool;
import com.franklin.maven.localcleaner.utils.MyCountDownLatch;
import com.google.common.collect.Lists;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.lang.ArrayUtils;
import org.jetbrains.idea.maven.project.MavenGeneralSettings;
import org.jetbrains.idea.maven.project.MavenProjectsManager;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * maven本地仓库检索器
 * @author: Ye Junhui
 * @since : 2022/4/2 0002
 */
public class LocalRepositoryFinder {

    /**
     * 删除jar包
     * @param project
     * @param packagePath
     * @throws IOException
     */
    public static void removeJar(Project project, String packagePath) throws IOException {
        VirtualFile localRepositoryPath = findLocalRepositoryPath(project);
        String path = localRepositoryPath.getPath() + "/" + packagePath;
        VirtualFile fileByIoFile = VfsUtil.findFileByIoFile(new File(path), true);
        if (Objects.isNull(fileByIoFile)){
            return;
        }

        VirtualFile[] children = fileByIoFile.getChildren();
        Object requestor = new Object();
        //添加排序
        Arrays.sort(children, Comparator.comparingInt(child -> {
            if (child.getName().contains(".jar")){
                return 0;
            }
            return 1;
        }));
        for (VirtualFile child : children) {
            child.delete(requestor);
        }
        fileByIoFile.delete(requestor);
    }

    /**
     * 查找maven仓库目录
     * @param project
     * @return
     */
    public static VirtualFile findLocalRepositoryPath(Project project){
        //获取idea配置本地maven仓库
        MavenGeneralSettings generalSettings = MavenProjectsManager.getInstance(project).getGeneralSettings();
        File effectiveLocalRepository = generalSettings.getEffectiveLocalRepository();

        //将路径转换为VF
        VirtualFile repositoryVF = VfsUtil.findFileByIoFile(effectiveLocalRepository, true);
        return repositoryVF;
    }

    /**
     * 根据maven配置找到maven本地仓库
     * @param project
     * @return
     */
    public static List<VirtualFile> findLocalPackages(Project project){
        VirtualFile repositoryVF = findLocalRepositoryPath(project);

        if (Objects.isNull(repositoryVF)){
            return Collections.emptyList();
        }

        VirtualFile[] children = repositoryVF.getChildren();
        if (ArrayUtils.isEmpty(children)){
            return Collections.emptyList();
        }

        //遍历子节点
        List<VirtualFile> virtualFileList = Lists.newCopyOnWriteArrayList();
        List<List<VirtualFile>> partitionChildren = Lists.partition(Lists.newArrayList(children), children.length / 4);
        MyCountDownLatch myCountDownLatch = new MyCountDownLatch(partitionChildren.size());
        partitionChildren.forEach(childList -> {
            ThreadPool.getExecutorService().execute(() -> {
                List<VirtualFile> childResultList = Lists.newArrayList();
                childList.forEach(child -> findMavenJarPackage(child,childResultList));
                virtualFileList.addAll(childResultList);
                myCountDownLatch.countDown();
            });
        });
        myCountDownLatch.await();

        return virtualFileList;
    }

    private static void findMavenJarPackage(VirtualFile target,List<VirtualFile> virtualFileList){
        if (Objects.isNull(target)){
            return;
        }
        if (target.exists()){
            VirtualFile[] children = target.getChildren();
            if (!ArrayUtils.isEmpty(children)){
                if (!children[0].isDirectory()) {
                    //找到了，直接添加父目录
                    virtualFileList.add(target);
                }else {
                    for (VirtualFile child : children) {
                        if (child.isDirectory()){
                            //递归查找
                            findMavenJarPackage(child,virtualFileList);
                        }
                    }
                }
            }
        }
    }
}
